//
//  DBVersionManager.m
//  DogeLegs
//
//  Created by 宋华 on 2017/8/25.
//  Copyright © 2017年 宋华. All rights reserved.
//

#import "DBVersionManager.h"
#import "DBHelper.h"
#import "DBConfigDefine.h"
#import "DBVersionMode.h"

@interface DBVersionManager () {

}

@property (nonatomic,strong)NSMutableArray *dbVersionArrs;

@end

@implementation DBVersionManager


- (void)dropDBVersionTable {
    FMDatabaseQueue* dbQueue = [[DBHelper getInstance] getDBQueue:IMDatabase];
    [dbQueue inDatabase:^(FMDatabase *db) {
            NSString *sql = [NSString stringWithFormat:@"DROP TABLE %@",TABLE_DBVersion];
            [db executeUpdate:sql];
    }];
}

/**
 @brief 单例
 @discussion 获取该类单例进行操作
 @return 返回类实例
 */
+ (DBVersionManager*)sharedInstance
{
    static dispatch_once_t onceBasicToken;
    
    static DBVersionManager *dbVerManager = nil;
    
    dispatch_once(&onceBasicToken, ^{
        dbVerManager = [[DBVersionManager alloc] init];
    });
    return dbVerManager;
}


//内部方法，检查数据库是否已经内部初始化过了
- (BOOL)isDatabaseHasInitInternal:(FMDatabaseQueue*)queue
{
    __block BOOL exists = NO;
    [queue inDatabase:^(FMDatabase *db) {
        FMResultSet* rs = [db executeQuery:@"select * from sqlite_master where type='table' and name='dbVersion'"];
        
        if([rs next]){
            exists = YES;
        }
        [rs close];
    }];
    return exists;
}

//内部方法，内部初始化数据库
- (void)initDatabaseInternal:(FMDatabaseQueue*)queue
{
    //创建dbVersion表
    [queue inDatabase:^(FMDatabase *db) {
        [db executeUpdate:@"create table dbVersion(curr_db_version integer not null,curr_msgDB_version integer not null,curr_recentMsgDB_version Integer not null,curr_app_version Integer not null,curr_allTable_version Integer not null)"];
        //插入一条数据
        [db executeUpdate:[NSString stringWithFormat:@"insert into dbVersion(curr_db_version,curr_msgDB_version,curr_recentMsgDB_version,curr_app_version,curr_allTable_version) values(%d,%d,%d,0,%d)",APP_DBVersion,CHATMSG_DBVersion,RECENT_DBVersion,AllTable_DBVersion]];
    }];
    
}

//内部方法，获取数据库版本号
- (int)getCurrDatabaseVersion:(FMDatabaseQueue*)queue
{
    __block int version = 0;
    [queue inDatabase:^(FMDatabase *db) {
        FMResultSet* rs = [db executeQuery:@"select curr_db_version from dbVersion"];
        if([rs next]){
            version = [rs intForColumnIndex:0];
        }
        [rs close];
    }];
    
    return version;
}

//内部方法，获取所有表的版本号
- (int)getCurrAllTableDBVersion:(FMDatabaseQueue*)queue {
    __block int version = 0;
    [queue inDatabase:^(FMDatabase *db) {
        FMResultSet* rs = [db executeQuery:@"select curr_allTable_version from dbVersion"];
        if([rs next]){
            version = [rs intForColumnIndex:0];
        }
        [rs close];
    }];
    
    return version;
}



//upradge数据库业务升级
- (void)upgradeBusiness:(int)oldVersion newVersion:(int)newVersion doneBlock:(void (^)(BOOL success))block {
    dispatch_group_t group  =dispatch_group_create();
    __block BOOL suc = YES;
    for (NSInteger i = 0; i <  self.dbVersionArrs.count; i++) {
        DBVersionMode *vMode = self.dbVersionArrs[i];
        if (vMode.curDBVersion > oldVersion && vMode.curDBVersion <= newVersion) {
            SEL sel = NSSelectorFromString(vMode.upardgeSelStr);
            
            dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                if ([self respondsToSelector:sel]) {
                    if (!suc) {//如果前面失败了就不在执行后面的了
                        suc = [self performSelector:sel];
                    }
                }
            });
        }
    }
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        if (block) {
            block(suc);
        }
    });
}


#pragma mark - getter
//版本为1只有@[1] 版本为2时有@[1,2],以此类推
- (NSMutableArray *)dbVersionArrs {
    if (_dbVersionArrs == nil) {
        _dbVersionArrs = [NSMutableArray array];
        [_dbVersionArrs addObject:[DBVersionMode upgradeOneMode]];
//        [_dbVersionArrs addObject:[DBVersionMode upgradeTwoMode]];
//        [_dbVersionArrs addObject:[DBVersionMode upgradeThreeMode]];
    }
    return _dbVersionArrs;
}


#pragma mark - 升级方法
- (BOOL)upgradeNoneToOne {
    NSLog(@"%@",NSStringFromSelector(_cmd));
    return YES;
}

- (BOOL)upgradeOneToTwo {
    NSLog(@"%@",NSStringFromSelector(_cmd));
    return YES;
}

- (BOOL)upgradeTwoToThree {
    NSLog(@"%@",NSStringFromSelector(_cmd));
    return YES;
}
#pragma mark - 暂时未用

//内部方法，获取聊天记录数据库版本号
- (int)getCurrMsgDatabaseVersion:(FMDatabaseQueue*)queue
{
    __block int version = 0;
    [queue inDatabase:^(FMDatabase *db) {
        FMResultSet* rs = [db executeQuery:@"select curr_msgDB_version from dbVersion"];
        if([rs next]){
            version = [rs intForColumnIndex:0];
        }
        [rs close];
    }];
    
    return version;
}


//内部方法，获取recent记录数据库版本号
- (int)getCurrRecentDatabaseVersion:(FMDatabaseQueue*)queue
{
    __block int version = 0;
    [queue inDatabase:^(FMDatabase *db) {
        FMResultSet* rs = [db executeQuery:@"select curr_recentMsgDB_version from dbVersion"];
        if([rs next]){
            version = [rs intForColumnIndex:0];
        }
        [rs close];
    }];
    
    return version;
}


//内部方法，内部升级数据库信息
- (void)upgradeDatabaseInternal:(FMDatabaseQueue*)queue dbVersion:(int)dbVersion
{
    //更新dbVersion表中的版本号
    [queue inDatabase:^(FMDatabase *db) {
        [db executeUpdate:@"update dbVersion set curr_db_version=?",[NSNumber numberWithInt:dbVersion]];
    }];
}

//内部方法，内部升级数据库信息
- (void)upgradeDatabaseInternal:(FMDatabaseQueue*)queue msgDBVersion:(int)msgDBVer
{
    //更新dbVersion表中的版本号
    [queue inDatabase:^(FMDatabase *db) {
        [db executeUpdate:@"update dbVersion set curr_msgDB_version=?",[NSNumber numberWithInt:msgDBVer]];
    }];
}

//内部方法，内部升级数据库信息
- (void)upgradeDatabaseInternal:(FMDatabaseQueue*)queue recentDBVersion:(int)curDBVersion
{
    //更新dbVersion表中的版本号
    [queue inDatabase:^(FMDatabase *db) {
        [db executeUpdate:@"update dbVersion set curr_recentMsgDB_version=?",[NSNumber numberWithInt:curDBVersion]];
    }];
}



@end
